
// const _ = require('lodash')
const crypto = require('crypto')

class WxUtil {
	/**
	 * 
	 * 产生随机字符串，不长于32位
	 * @param int $length
	 * @return 产生的随机字符串
	 */
	static getNonceStr(length = 32) {
		const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
		let str = ""
		for (let i = 0; i < length; i++ )  {  
			str += chars.substr(Math.round(Math.random() * (chars.length -1)), 1)
		} 
		return str
	}

	/**
	 * 
	 * json转xml字符
	 * @throws WxPayException
	**/
	static jsonToXml(values) {
		let arrKeys = Object.keys(values)
		if(arrKeys.length == 0){
    		throw new Error("数组数据异常！")
    	}
    	
    	let xml = "<xml>"
    	arrKeys.forEach((key)=> {
    		// if(typeof values[key] === 'number') {
    		if(!isNaN(values[key])) {
    			xml += "<" + key + ">" + values[key] + "</" + key + ">"
    		}else {
    			xml += "<" + key + "><![CDATA[" + values[key] + "]]></" + key + ">"
    		}
    	})
    	
        xml += "</xml>"
        return xml 
	}

    /**
     * wx jsapi_sdk的签名
     * @param config  {noncestr, jsapi_ticket, timestamp, url}
     * @return string sign
     */  
    static makeJsapiSign(config) {
        let sign = ''
        // 按字典序排序参数,&拼接
        Object.keys(config).sort().forEach(k=> {
            sign += k + "=" + config[k] + "&"
        })
        sign = sign.slice(0, -1)
        sign = crypto.createHash('sha1').update(sign).digest('hex')
        return sign
    }

	/**
	 * wx支付生成签名
	 * @param config  配置对象
	 * @param key 为商户平台设置的密钥key
	 * @return string sign
	 */
	static makeSign(config, key, SignType='md5') {
		let sign = ''
		// 签名步骤一：按字典序排序参数,&拼接
		Object.keys(config).sort().forEach(k=> {
			if (k !== 'sign' && typeof config[k] != 'object' && config[k] != '') sign += k + "=" + config[k] + "&"
		})
		// 签名步骤二：在string后加入KEY
		sign += 'key=' + key
		//签名步骤三：MD5加密(默认) 还有（HMAC-SHA256）
		if (SignType === 'md5') sign = crypto.createHash(SignType).update(sign).digest('hex')
		else if (SignType === 'sha256') sign = crypto.createHmac(SignType, key).update(sign).digest('hex')
		//签名步骤四：所有字符转为大写
		sign = sign.toUpperCase()
		return sign
	}
}

module.exports = WxUtil